package com.htjx.mall.admin.controllers;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.htjx.mall.admin.controllers.vo.BrandQuery;
import com.htjx.mall.commons.api.CommonConstant;
import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.product.Brand;
import com.htjx.mall.commons.utils.Dates;
import com.htjx.mall.commons.utils.page.Page;
import com.htjx.mall.services.BrandService;

@Controller
@RequestMapping("/admin/brand")
public class _BrandController {
	@Autowired
	private BrandService brandService;
	
	/****
	 * 查询商品种类
	 * @param productQuery
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(BrandQuery brandQuery, Model model) {
		Page<Brand> page = new Page<Brand>();
		page.setPageSize(brandQuery.getPageSize());
		page.setPageNo(brandQuery.getPageNo());
		page = brandService.page(brandQuery, page);
		
		model.addAttribute("page", page);
		return "brand/list";
	}
	
	@RequestMapping(value = "/add", method=RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("brand", new Brand());
		return "brand/add";
	}
	
	/****
	 * 新增一个种类
	 * @param productQuery
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add", method=RequestMethod.POST)
	public String add(Brand brand, @RequestParam("img_file") MultipartFile imgFile, Model model, HttpServletRequest request) {
		String name = brand.getName();
		if(StringUtils.isBlank(name)) {
			model.addAttribute("result", new Result(9,"请填写种类名称"));
			return "brand/add";
		}
		
		if(brandService.checkUniqueByProperty("name", name)) {
			model.addAttribute("result", new Result(9,"该种类已被添加"));
			return "brand/add";
		}
		
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isNotBlank(originalFileName)) {
			if(!checkImage(imgFile)) {
				model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
				return "brand/add";
			}
			brand.setImage(saveImage(imgFile, request));
		} else {
			brand.setImage(null);
		}
		
		String description = brand.getDescription();
		if(StringUtils.isBlank(description)) {
			model.addAttribute("result", new Result(9,"请填写种类描述"));
			return "brand/add";
		}
		
		brand.setCreate_time(new Date());
		brandService.insertOne(brand);
		model.addAttribute("result", new Result(0,"种类添加成功"));
		return "redirect:list";
	}
	
	@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
	public String detail(@PathVariable("id") long id, Model model) {
		Brand brand = brandService.selectById(id);
		Result result = null;
		if(brand == null) {
			result = new Result(9,"查询商品失败");
		} 
		
		model.addAttribute("result", result);
		model.addAttribute("brand", brand);
		return "brand/detail";
	}
	
	@RequestMapping(value="/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") long id, Model model) {
		Brand brand = brandService.selectById(id);
		model.addAttribute("brand", brand);
		return "brand/update";
	}
	
	@RequestMapping(value="/update", method = RequestMethod.POST)
	public String update(Brand brand, @RequestParam(value = "img_file", required=false) MultipartFile imgFile, Model model, HttpServletRequest request) {
		Brand ref = brandService.selectById(brand.getId());
		if(ref == null) {
			Result result = new Result(9, "数据有误");
			model.addAttribute("result", result);
			return "redirect:/admin/brand/detail/"+brand.getId();
		}
		
		String name = brand.getName();
		if(StringUtils.isBlank(name)) {
			model.addAttribute("result", new Result(9,"请填写品类名称"));
			return "redirect:/admin/brand/detail/"+brand.getId();
		}
		
		String cn_name = brand.getCn_name();
		if(StringUtils.isBlank(cn_name)) {
			model.addAttribute("result", new Result(9,"请填写品类名称"));
			return "redirect:/admin/brand/detail/"+brand.getId();
		}
		
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isNotBlank(originalFileName)) {
			if(!checkImage(imgFile)) {
				model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
				return "product/update";
			}
	        brand.setImage(saveImage(imgFile, request));
		} 
				
		brandService.updateOne(brand);
		return "redirect:/admin/brand/list";
	}
	
	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable("id") long id) {
		brandService.deleteOne(id);
		return "redirect:/admin/brand/list";
	}
	
	private boolean checkImage(MultipartFile imgFile) {
		return true;
	}
	
	
	private String saveImage(MultipartFile imgFile, HttpServletRequest request) {
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		String fileType = imgFile.getOriginalFilename().substring(originalFileName.lastIndexOf("."));
		String filePath = CommonConstant.SHARE_PATH+Dates.toYYYY_MM_DD(new Date())+"/images";
		String realPath = request.getSession().getServletContext().getRealPath(filePath); 
	    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
			
		String fileName = Dates.toTimeString(new Date()) + fileType;
        try {
			FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, fileName));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
        String image_src = filePath+"/"+fileName;
        return image_src;
	}
}
